package com.ycy.login;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ycy.pojo.Employee;
import com.ycy.service.employee.EmployService;

@Controller
public class LoginController {

	@Autowired
	VerifiCode verifiCode;
	@Autowired
	EmployService employservice;
	
	@RequestMapping("/verificode")
	 public void Verificode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       /*
        1.生成验证码
        2.把验证码上的文本存在session中
        3.把验证码图片发送给客户端
        */
       VerifiCode v=new VerifiCode();     //用我们的验证码类，生成验证码类对象
       BufferedImage image=v.getImage();  //获取验证码
       request.getSession().setAttribute("TEXT", v.getText()); //将验证码的文本存在session中
       v.output(image, response.getOutputStream());//将验证码图片响应给客户端
   }
	
	@RequestMapping("/dologin")
	public String login(HttpServletRequest request, @Valid Employee employee,BindingResult result,RedirectAttributes redirectAttributes,HttpSession session
			){
		
		 
		if (result.hasErrors()) {  
            List<ObjectError> list = result.getAllErrors();  
            for (ObjectError error : list) {  
            	request.setAttribute("message", error.getDefaultMessage()); 
            }  
            return "login";  
        }  
		 String session_vcode=(String) request.getSession().getAttribute("TEXT");    //从session中获取真正的验证码
	     String form_vcode=request.getParameter("vcode"); //获取用户输入的验证码
	     if(!(session_vcode.equalsIgnoreCase(form_vcode))){
	    	 redirectAttributes.addFlashAttribute("message", "验证码错误");
	         return "redirect:login";
	         }
		   	Subject currentemployee = SecurityUtils.getSubject();
	        if (!currentemployee.isAuthenticated()) {
	        	
	        	 String nickname=employee.getNickname();
	        	 String password =employee.getPassword();
	        	
	        	 UsernamePasswordToken token = new UsernamePasswordToken(nickname, password);
	          
	            try {
	                currentemployee.login(token);
	               Subject subject= SecurityUtils.getSubject();
	           String name= (String) subject.getPrincipal();
	          Employee me= employservice.findit(name);
	          session.setAttribute("Me", me);
	          } 
	            catch (AuthenticationException ae) {
	            	
	            	redirectAttributes.addFlashAttribute("message", "密码或用户名错误");
	            	return "redirect:login";
	            }
	        } 
	
	        return "redirect:index";
	        } 
	}
